package com.example.EatOnTrojans;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;


import com.example.EatOnTrojans.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class RouteMapsActivity extends MapActivity {
    /** Called when the activity is first created. */
	
	LocationManager locationManager;
	MapView mapView;
	MapController mMapController;
	HelloItemizedOverlay itemizedoverlayCurrent;
	HelloItemizedOverlay itemizedoverlayDine;
	private ImageButton mainButton;
	String rest[]=new String[10];
	public String name;
	public String location;
	public String type;
	public String cuisine;
	public String openHour;
	public String menu;
	public float rate;
	public float lat1;
	public float lng1;
	public String imageURL;
	public String routeURL;
	public String content;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.route);
        
        Bundle bundle = this.getIntent().getExtras();
        
		rest = bundle.getString("detial").split(";");
		name=rest[0];
		location=rest[1];
		type=rest[2];
		cuisine=rest[3];
		openHour=rest[4];
		menu=rest[5];
		imageURL=rest[6];
		rate=Float.parseFloat(rest[7]);
		lat1=Float.parseFloat(rest[8]);
		lng1=Float.parseFloat(rest[9]);
		
		content=location+";"+type+";"+cuisine+";"+openHour+";"+imageURL+";"+rate;
		/* set map control */
        
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);

        mapView.setTraffic(false);
        mapView.setSatellite(false);
        mMapController = mapView.getController();  
        
        List<Overlay> mapOverlays = mapView.getOverlays(); //set location overlay
        
        /* set item overlay */
        Drawable drawable1 = this.getResources().getDrawable(R.drawable.ic_launcher);
        itemizedoverlayCurrent = new HelloItemizedOverlay(drawable1, this);
        
        Drawable drawable = this.getResources().getDrawable(R.drawable.pin);
        itemizedoverlayDine = new HelloItemizedOverlay(drawable, this);
        
        float lat = 34.020668f;
        float lng = -118.289645f;
        GeoPoint point = new GeoPoint((int)(lat * 1E6), (int)(lng * 1E6));
        routeURL="http://maps.google.com/maps/api/directions/xml?origin="+lat+","+lng+"&destination="+lat1+","+lng1+"&sensor=false&mode=walking";
        mMapController.animateTo(point);
        mMapController.setZoom(19);
        
        OverlayItem overlayitem = new OverlayItem(point, "Current Location", "Leavey");
        itemizedoverlayCurrent.addOverlay(overlayitem);
        mapOverlays.add(itemizedoverlayCurrent);
        
        GeoPoint point1 = new GeoPoint((int)(lat1 * 1E6), (int)(lng1 * 1E6));
        OverlayItem overlayitem1 = new OverlayItem(point1, name, content);
        itemizedoverlayDine.addOverlay(overlayitem1);
        
        drawRoute(routeURL);
        
        mapOverlays.add(itemizedoverlayDine);
        
        mainButton=(ImageButton)findViewById(R.id.imageButton1);
        
        mainButton.setOnClickListener(new ImageButton.OnClickListener(){
			@Override
			public void onClick(View v){
				//Toast.makeText(getApplicationContext(), "click the image",Toast.LENGTH_SHORT).show();
				Intent intent = new Intent();
				intent.setClass(RouteMapsActivity.this, EatOnTrojansActivity.class);
				RouteMapsActivity.this.startActivity(intent);
			}
		});
		
    }
    
	private List<GeoPoint> decodePoly(String encoded) {

	    List<GeoPoint> poly = new ArrayList<GeoPoint>();
	    int index = 0, len = encoded.length();
	    int lat = 0, lng = 0;

	    while (index < len) {
	        int b, shift = 0, result = 0;
	        do {
	            b = encoded.charAt(index++) - 63;
	            result |= (b & 0x1f) << shift;
	            shift += 5;
	        } while (b >= 0x20);
	        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
	        lat += dlat;

	        shift = 0;
	        result = 0;
	        do {
	            b = encoded.charAt(index++) - 63;
	            result |= (b & 0x1f) << shift;
	            shift += 5;
	        } while (b >= 0x20);
	        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
	        lng += dlng;

	        GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
	             (int) (((double) lng / 1E5) * 1E6));
	        poly.add(p);
	    }

	    return poly;
	}
	
	
	public void drawRoute(String url){
			
		HttpGet get = new HttpGet(url);
		String strResult = "";
		try {
			HttpParams httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
			HttpClient httpClient = new DefaultHttpClient(httpParameters); 
			
			HttpResponse httpResponse = null;
			httpResponse = httpClient.execute(get);
			
			if (httpResponse.getStatusLine().getStatusCode() == 200){
				strResult = EntityUtils.toString(httpResponse.getEntity());
			}
		} catch (Exception e) {
			return;
		}
		
		if (-1 == strResult.indexOf("<status>OK</status>")){
			Toast.makeText(this, "Fail to get the route!", Toast.LENGTH_SHORT).show();
			this.finish();
			return;
		}
		
		int pos = strResult.indexOf("<overview_polyline>");
		pos = strResult.indexOf("<points>", pos + 1);
		int pos2 = strResult.indexOf("</points>", pos);
		strResult = strResult.substring(pos + 8, pos2);
		
		List<GeoPoint> points = decodePoly(strResult);
		
		MyOverLay mOverlay = new MyOverLay(points);
		List<Overlay> overlays = mapView.getOverlays();
		overlays.add(mOverlay);
		
		if (points.size() >= 2){
			mMapController.animateTo(points.get(0));
		}
		 
		mapView.invalidate();
	}

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    private class HelloItemizedOverlay extends ItemizedOverlay{

    	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    	Context mContext;
    	private String restaurantConent[]=new String[10];
    	
    	public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
    		super(boundCenterBottom(defaultMarker));
    		mContext = context;
    		// TODO Auto-generated constructor stub
    	}
    	
    	public void addOverlay(OverlayItem overlay) {
    	    mOverlays.add(overlay);
    	    populate();
    	}
    	
    	public void addNewItem(GeoPoint location,String marketText,String snippet)
        {
    		mOverlays.add(new OverlayItem(location,marketText,snippet));
            populate();
        }
    	
    	public void removeItem(int index)
        {
    		mOverlays.remove(index);
            populate();

        }
    	
    	@Override
    	protected OverlayItem createItem(int i) {
    		return mOverlays.get(i);
    	}
    	
    	@Override
    	public int size() {
    		return mOverlays.size();
    	}
    	
    	@Override
    	protected boolean onTap(int index) {
    		OverlayItem item = mOverlays.get(index);
    		
    		final Dialog dialog = new Dialog(mContext);
    		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    		dialog.setContentView(R.layout.dialog);
    	
    		// set the custom dialog components - text, image and button
    		TextView textView1 = (TextView) dialog.findViewById(R.id.diagName);
    		TextView textView2 = (TextView) dialog.findViewById(R.id.diagLoc);
    		TextView textView5 = (TextView) dialog.findViewById(R.id.diagHour);
    		TextView textView3 = (TextView) dialog.findViewById(R.id.diagRev);
    		TextView textView4 = (TextView) dialog.findViewById(R.id.diagRate);
    		//TextView textView5 = (TextView) dialog.findViewById(R.id.textView5);
    		Button button1 = (Button) dialog.findViewById(R.id.diagBut);
    		button1.setText("Post on Facebook");
    		
    		restaurantConent=item.getSnippet().split(";");
    		
    		textView1.setText(name);
    		textView1.setPadding(10, 0, 20, 0);
    		textView2.setText("Location: "+location);
    		textView2.setPadding(10, 0, 20, 0);
    		textView5.setText("Hour: "+openHour);
    		textView5.setPadding(10, 0, 20, 0);
    		textView3.setText(type+": "+cuisine);
    		textView3.setPadding(10, 0, 20, 0);
    		textView4.setText("Menu: "+menu);
    		textView4.setPadding(10, 0, 20, 0);
    		
    		RatingBar mRatingBar = (RatingBar) dialog.findViewById(R.id.diagStar);
    		mRatingBar.setNumStars(5);
    		mRatingBar.setRating(rate);
    		
    		ImageView image = (ImageView) dialog.findViewById(R.id.diagImg);
        	//Bitmap bm = getBitmap(imageURL);
    		//image.setImageBitmap(bm);
    		int imageResource=Integer.parseInt(imageURL);
    		image.setImageResource(imageResource);
    		
    		image.setMaxHeight(130);
    		image.setMaxWidth(130);
    		image.setPadding(10, 0, 20, 0);
    		
    		//display dialog
    		dialog.show();
    		dialog.setCanceledOnTouchOutside(true);
    		
    		ImageView cancel = (ImageView) dialog.findViewById(R.id.cancel);
    		cancel.setOnClickListener(new View.OnClickListener(){
	        	public void onClick(View v){
	        		dialog.dismiss();
	        	}
	        });
    		
    		button1.setOnClickListener(new View.OnClickListener() {
    			public void onClick(View v) {
    				
    			}
            });
    		
    		return true;
    	}
    		
    	//get image from URL
    	public Bitmap getBitmap(String imageURL){ 
    		//initialize bitmap
    		Bitmap mBitmap = null; 
    		try { 
    			//open connection to the URL
    			URL url = new URL(imageURL); 
    			URLConnection conn = url.openConnection(); 
    			conn.connect();
    			InputStream is = conn.getInputStream(); 
    			BufferedInputStream buff = new BufferedInputStream(is);
    			//get image stream
    			mBitmap = BitmapFactory.decodeStream(buff); 
    			buff.close();
    			is.close();
    		} catch (MalformedURLException e) { 
    			e.printStackTrace(); 
    		} catch (IOException e) { 
    			e.printStackTrace(); 
    		} 
    		return mBitmap; 
    	} 
    }
    
}